﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QunProject.Common;
using EnumHelper = QunProject.Model.EnumHelper;

namespace QunProject.Manage.Controllers
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginController : BaseController
    {
        // 登录页
        public ActionResult Index()
        {
            if (LoginUser != null)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
        // 登录验证码
        public JsonResult AjaxLoginCode()
        {
            string code = Common.RanString.RandomNumber(4);
            string base64 = Common.Security.VerifiedImage(code).ToBase64();
            LoginCode = code;
            return Json(Result.Success(base64));
        }
        // 提交登录信息
        public JsonResult AjaxLoginSubmit(string account, string password, string code)
        {
            if (!Common.Verify.VerifyLength(account, 5, 16))
                return Json(Result.Fail("用户名格式错误"));
            if (!Common.Verify.VerifyLength(password, 6, 18))
                return Json(Result.Fail("密码格式错误"));
            if (code.Length != 4)
                return Json(Result.Fail("验证码格式错误"));
            if (LoginCode == null)
                return Json(Result.Fail("请获取验证码"));
            if (LoginCode != code)
                return Json(Result.Fail("验证码错误"));

            string _password = Common.Security.MD5Encrypt32(password);
            var user = EF.sys_user.SingleOrDefault(x => x.Account == account && x.Password == _password && x.IsValid.Value);
            if (user == null)
                return Json(Result.Fail("用户名或密码错误"));

            LoginUser = user;
            return Json(Result.Success());
        }

    }
}